package com.lx.wx.restful.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.lx.pc.domain.vo.wx.WeixinVo;
import com.lx.pc.utils.Constants;

public class WeiXinUtils {

	
	
	
	public static void main(String[] args) {
		/**
		 * 获取token
		 */
//		WeixinVo weixinVo = new WeixinVo();
//		JSONObject json = WeiXinUtils.getAccessToken(weixinVo);
//		System.out.println(json);
//		String access_token = json.getString("access_token");
//		System.out.println("access_token---" + access_token);
		
		//String access_token = "12_kAGYpJdl1lIkVUynfgzMeLJD5p5jkIhlZSxcm8367Hy8zpFP5hF-REtWBbb04GTKzuIZegcMbUNYmXHdSkT6OCRKqKUYu7BLOyfFAFpOj4TQJ9nL5VcPFKXeLWdS_w5AQE1bIDBYwqVcARUpRHDdAAAWMI";

		// String urls =
		// "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
		// String urls = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" +
		// access_token + "&next_openid=";
		// 3、时间戳和随机字符串
		/*
		 * String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0,
		 * 16);//随机字符串 String timestamp = String.valueOf(System.currentTimeMillis() /
		 * 1000);//时间戳
		 * 
		 * String jsapi_ticket = jsonObject1.getString("ticket");
		 * 
		 * System.out.println(access_token); System.out.println(jsapi_ticket);
		 * System.out.println(noncestr); System.out.println(timestamp);
		 */
		//获取非静默授权用户 openId
		//JSONObject json = WeiXinUtils.getUserInfo(request);
		
		//String refresh_token = "12_pnysOgDtOLdKmt_G1J6DhO-xqgW3LSZJZA94S9lsCM9CLO7c1AOJ9QBJn58UUysfVNI4VS2rJr9F6E6ZStxY95oqhaFuVY0ncNgZ9yN9rZg";
		
	    /*JSONObject json111 = getUserInfo("081LEsmM1N4Vg41wQepM1k0amM1LEsm-");
	    System.out.println(":"+json111);
	    
	    String openId = json111.getString("openid");
	    System.out.println(openId);*/
		/*JSONObject jsonObject = new JSONObject();
		String token = "12_dQMPndUMzusfqNaldSM7K5d5KdeJbDT0UJTmNu0v8zuU7jCiCQ17IgUaGD5CXJHHgFPEeDONe2TXpll3tHbsL57D3I7anGJrAY5G7WkRvG0Qx7QPqMbYOvQRIv0KHVbADAYVJ";
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid=oX_AN1G2e5c8-eIEvWnWDGYjrPi8&lang=zh_CN";
		JSONObject jsonObject1 = httpRequest(url, "GET", jsonObject);
		String nickname = jsonObject1.getString("nickname");
		String headimgurl = jsonObject1.getString("headimgurl");
				System.out.println(nickname);
		System.out.println(jsonObject1);*/
		
		
	   // senMsg("oX_AN1G2e5c8-eIEvWnWDGYjrPi8","12_7H7fzhNE9QLX_08ExWrPKQEotrgZIL-RMb4AQRF8x-8FPveXggDfarZWaaH8Q1SQfjoTzcaYyRZzumRywglGyW6qa0qOnHrdROwFGFrBeylxWi3RtrQiqsWOYh0uL8SO6lrhbgIEaHZ2HxvXSFQcACAANY");
	
		//发送消息模版
  		Map<String,TemplateData> par = new HashMap<>();
  		par.put("first",new TemplateData("接单啦","#696969"));
  		par.put("tradeDateTime",new TemplateData("2018-08-13 17:14:35","#696969"));
  		par.put("orderType",new TemplateData("进行中","#696969"));
  		par.put("customerInfo",new TemplateData("联系人","#696969"));
  		par.put("orderItemName",new TemplateData("113131","#696969"));
  		par.put("orderItemData",new TemplateData("orderItemData","#696969"));
  		par.put("remark",new TemplateData("预约时间：15-31 \r\n"
  	        		+"123"
  	        		+ "请提前与用户联系 \r\n","#696969"));
  		//调用发送微信消息给回收员的接口
        WeiXinUtils.sendWechatMsgToReceipt("12_8mu7Tdonvv9Z3mzVkIDUXae1jBKgCcTW9FrspQsatKJRR9vQNiPb4RH09xxTpT1NTejzaZTdRtIwImJ9GwfMWuIfy6P9UCy-uFQ2TTmKSmlToIBcHSAdbhE8YfECMMjvxYE2x5ySWLZXDIXmKEKgAGAWQW",
        		"oX_AN1BUlJ6nYLY9oSKGMnWikCzg",Constants.RECEIPT, "", "#000000", WeiXinUtils.packJsonmsg(par));
	}
	

	public static JSONObject getAccessToken(WeixinVo weixinVo) {
		
		//获取微信token
		String access_token = "";
		String expires_in = "";
		
		//获取tonken
		JSONObject jsonObject = new JSONObject();
		String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constants.APPID+"&secret="+Constants.APPSECRET;
		JSONObject jsonObject1 = httpRequest(getTokenUrl, "GET", jsonObject);
		
		if (null != jsonObject) {
			try {
				access_token = jsonObject1.getString("access_token");
				expires_in = jsonObject1.getString("expires_in");
			} catch (JSONException e) {
				access_token = null;
			}
		}
		
		JSONObject jsonObject2 = new JSONObject();
		jsonObject2.put("access_token", access_token);
		jsonObject2.put("expires_in", expires_in);
		jsonObject2.put("appId", Constants.APPID);

		return jsonObject2;
	}
	
	/**
	 * 获取非静默授权 获取用户openId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getUserInfo(String code){

		// 微信官方提供的url规范
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.APPID + "&secret="
				+ Constants.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
		JSONObject json = httpRequest(url, "GET", null);
		return json;
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, JSONObject outputStr) {

		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();

		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new WeixinX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))

				httpUrlConn.connect();

			// 当有数据需要提交时
			if (outputStr != null && null != outputStr.toString()) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.toString().getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());

		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}
	

	/**
	 * 判断token 是否过期，重新获取token
	 * 
	 * @param tokenTime
	 * @return
	 * @throws ParseException
	 */
	public static boolean time(String tokenTime) throws ParseException {
		Calendar calendar = Calendar.getInstance();
	    calendar.add(Calendar.HOUR, 2);
	    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String format = df.format(calendar.getTime());
		// 获取当前系统时间
	    
		Date parseStr = df.parse(tokenTime);
		long timeStr = parseStr.getTime();
		Date parse2Before = df.parse(format);
		long time2Before = parse2Before.getTime();
		long timeNew = (new Date()).getTime();
		
		if(timeStr-time2Before >= 0) {
			System.out.println("在两小时之内~~~~啦啦啦啦");
			return false;
		}else {
			System.out.println("不在两小时之内~~~~lalalalala");
			return true;
		}
		
	}
	
	public static boolean time2(String tokenTime) throws ParseException{
		//获取当前系统时间
		long time2 = System.currentTimeMillis();
		Date date = new Date(time2);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		//获取2小时后的日期
        Date dt = dateFormat.parse(tokenTime.substring(0,13));
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.HOUR,2);//日期加10天
        Date dt1=rightNow.getTime();
        String reStr = dateFormat.format(dt1);
		String time = dateFormat.format(date);
        
        Date date2 = dateFormat.parse(reStr);
        Date date3 = dateFormat.parse(time);
        System.out.println(time);
        if ( date2.before(date3)) {
            System.out.println("xiaoyu");
            return false;
        }else{
            System.out.println("dayu");
            return true;
        }
        
	}

	/**
	 * sha1签名
	 * 
	 * @param url
	 * @return
	 */
	public static String getSha1(String url) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(url.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static JSONObject packJsonmsg(Map<String, TemplateData> param) {
        JSONObject json = new JSONObject();
        for (Map.Entry<String,TemplateData> entry : param.entrySet()) {
            JSONObject keyJson = new JSONObject();
            TemplateData  dta=  entry.getValue();
            keyJson.put("value",dta.getValue());
            keyJson.put("color", dta.getColor());
            json.put(entry.getKey(), keyJson);
        }
        return json;
    }
	
	public static String sendWechatMsgToUser(String token,String touser, String templatId, String clickurl, String topcolor, JSONObject data) {
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        JSONObject json = new JSONObject();
        json.put("touser", touser);
        json.put("template_id", templatId);
        json.put("url", clickurl);
        json.put("topcolor", topcolor);
        json.put("data", data);
        try{
            JSONObject result = httpRequest(tmpurl, "POST", json);
            System.out.println("message-----" + result);
            JSONObject resultJson = new JSONObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
         }catch(Exception e){
            e.printStackTrace();
            return "error";
        }
        return "success";
   }
	
	//
	public static String sendWechatMsgToReceipt(String token,String touser, String templatId, String clickurl, String topcolor, JSONObject data) {
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        JSONObject json = new JSONObject();
        json.put("touser", touser);
        json.put("template_id", templatId);
        json.put("url", clickurl);
        json.put("topcolor", topcolor);
        json.put("data", data);
        try{
            JSONObject result = httpRequest(tmpurl, "POST", json);
            System.out.println("message-----" + result);
            JSONObject resultJson = new JSONObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
         }catch(Exception e){
            e.printStackTrace();
            return "error";
        }
        return "success";
   }
	
	public static void senMsg(String openId,String token){
		Map<String,TemplateData> param = new HashMap<>();
        param.put("first",new TemplateData("恭喜您下单成功！","#696969"));
        param.put("OrderSn",new TemplateData("15618551533","#696969"));
        param.put("OrderStatus",new TemplateData("2017年05月06日","#696969"));
        
        String c = "废纸类：10-50kg \r\n废塑料类：50-100kg \r\n";
        param.put("remark",new TemplateData("祝投资愉快！\r\n" + c ,"#696969"));
        //注册的微信-模板Id
        String regTempId =  "Z_8HZpHJ2hQieTPk85v7jGNoKykoN4UstuJixn7qlFg";
        //调用发送微信消息给用户的接口
        
        sendWechatMsgToUser(token,openId,regTempId, "", "#000000", packJsonmsg(param));
	}
}
